<template>
  <div :class="styles.container">
    <div :class="styles.title">
      <div>找阿姨</div>
      <div>找工作</div>
      <div>就上阿姨直聘</div>
    </div>
    <div :class="styles.login">
      <div v-show="!checked" @click="validateChecked" :class="styles.cover"></div>
      <button
        type="primary"
        openType="getPhoneNumber|agreePrivacyAuthorization"
        :class="styles.loginBtn"
        @getphonenumber="loginHandle"
      >
        授权并登录
      </button>
      <div :class="styles.privacy">
        <checkbox-group @change="checkedChange">
          <checkbox :class="styles.checkbox">阅读并同意</checkbox>
        </checkbox-group>
        <span @click="showPrivacy" :class="styles.text">《阿姨直聘隐私政策》</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { onMounted, ref } from 'vue';
import Taro from '@tarojs/taro';
import Native from '@/utils/native';
import { useUser } from '@/stores';
import { PRIVACY_POLICY } from '@/const/h5';
import styles from './index.module.less';

export default {
  setup() {
    const code = ref('');
    const checked = ref(false);

    /** 页面初始化时候先登录获取code */
    const getCode = async () => {
      const { code: _code } = await Taro.login({
        timeout: 5000,
      });
      code.value = _code;
    };
    const userStore = useUser();
    onMounted(() => {
      getCode();
    });

    // eslint-disable-next-line complexity
    const loginHandle = async (res) => {
      const { errMsg } = res.detail;
      try {
        if (errMsg === 'getPhoneNumber:ok' && code.value) {
          Native.showLoading('登录中');
          await Taro.checkSession();
          await userStore.authLogin(code.value, res.detail);
          Native.showToast('登录成功');
          // if (redirect.value.path) {
          //   const token = ((await Storage.getItem('token')) || '') as string;
          //   const originUrl = decodeURIComponent(redirect.value.path);
          //   Native.redirectTo(ParamsUtil.addParams(originUrl, { token }));
          // } else {
          //   Native.redirectTo('/pages/index/index');
          // }
          Taro.navigateBack();
        } else throw new Error('登录失败');
      } catch (err) {
        Native.showToast(err.message, {
          icon: 'none',
        });
      }
    };

    const validateChecked = () => {
      Taro.showToast({
        title: '请先同意隐私政策',
        icon: 'none',
      });
    };

    const showPrivacy = () => {
      Taro.navigateTo({
        url: `/pages/webview/index?redirect=${encodeURIComponent(PRIVACY_POLICY)}`,
      });
    };

    const checkedChange = (e) => {
      checked.value = !!e.detail.value.length;
    };

    return {
      styles,
      checked,
      loginHandle,
      showPrivacy,
      checkedChange,
      validateChecked,
    };
  },
};
</script>
